package com.lwm.jdbc;

import java.sql.*;

/**
 * 程序的耦合
 *
 * @author liweimin
 * @date 2021/6/1 16:06
 * @since
 */
public class JdbcApplication {

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        // 1.注册驱动
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

        //使用反射去创建对象避免直接new 关键实例化对象----->解耦
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");


        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/demo", "root", "root");

        return connection;
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        /**
         * 1.注册驱动
         * 2.获取连接
         * 3.获取操作数据库的预处理对象
         * 4.执行SQL，获得结果集
         * 5.遍历结果集
         * 6.释放资源
         */
        // 1.注册驱动
//        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
//
//        //2.获取连接
//        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/demo", "root", "root");
        Connection connection = getConnection();
        //3.获取操作数据库的预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement("select  * from user");
        //4.执行SQL，获得结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        //5.遍历结果集
        while (resultSet.next()) {
            System.out.println(resultSet.getString("name"));
        }
        //6.释放资源--->实际放在finally中
        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}
